import { defineStore } from "pinia";
import { createDispatchList } from "@/api/fis";
import { ref } from "vue";
import { ElMessage } from "element-plus";

export const useDispatchlistStore = defineStore("dispatchList", () => {
  const invoiceParts = ref([]);
  const uuid = ref("");
  const isLoading = ref(false);

  const funDispatchList = async (data) => {
    isLoading.value = true;
    try {
      const res = await createDispatchList(data);

      // 数据验证
      if (!res || typeof res !== "object") {
        throw new Error("返回数据格式不正确");
      }

      if (!res.uuid || typeof res.uuid !== "string") {
        throw new Error("缺少或无效的UUID");
      }

      if (!Array.isArray(res.invoiceParts)) {
        throw new Error("发票部件数据格式不正确");
      }

      // 添加索引并更新状态
      invoiceParts.value = res.invoiceParts.map((item, index) => ({
        ...item,
        index: index + 1,
        //后期需要在接口中写好
        type: "顶棚"
      }));

      uuid.value = res.uuid;

      return res;

    } catch (error) {
      // console.error("创建派单列表失败:", error);
      ElMessage.error("序号输入错误");
      invoiceParts.value = [];
      uuid.value = "";
      throw error;
    } finally {
      isLoading.value = false;
    }
  };

  // 重置状态的函数
  const resetStore = () => {
    invoiceParts.value = [];
    uuid.value = "";
  };

  return {
    funDispatchList,
    resetStore,
    invoiceParts,
    uuid,
    isLoading
  };
});